package com.bdzl.biz.service.impl;

import com.bdzl.biz.dao.AgentDao;
import com.bdzl.biz.feign.FeignloanAdmin;
import com.bdzl.biz.service.AgentRelBankcardService;
import com.bdzl.biz.service.AgentService;
import com.bdzl.biz.servicefeign.AdminBankcardFeignService;
import com.bdzl.biz.servicefeign.AdminEnterpriseFeignService;
import com.bdzl.pub.entity.data.BankcardDO;
import com.bdzl.pub.entity.data.EnterpriseDO;
import com.bdzl.pub.entity.loan.AgentDO;
import com.bdzl.pub.entity.loan.AgentRelBankcardDO;
import com.bdzl.pub.entity.sys.FileDO;
import com.bdzl.pub.enums.FileEnum;
import com.bdzl.pub.util.file.BASE64DecodedMultipartFile;
import com.bdzl.pub.util.file.OssUploadFileUtil;
import com.bdzl.pub.util.param.PageUtils;
import com.bdzl.pub.util.param.R;
import com.bdzl.pub.util.validUtils.ValidList;
import com.bdzl.pub.vo.EnterpriseVO;
import com.bdzl.pub.vo.data.AgentVO;
import com.bdzl.pub.vo.data.BankcardVO;
import org.apache.commons.beanutils.BeanUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Transactional(rollbackFor = Exception.class)
public class AgentServiceImpl implements AgentService {
    @Autowired
    private AgentDao agentDao;
    @Autowired
    private AgentRelBankcardService agentRelBankcardService;
    @Autowired
    private FeignloanAdmin feignloanAdmin;
    @Autowired
    private AdminBankcardFeignService adminBankcardFeignService;
    @Autowired
    private AdminEnterpriseFeignService adminEnterpriseFeignService;

    @Override
    public AgentDO get(Integer agentId) {
        return agentDao.get(agentId);
    }

    @Override
    public List<AgentDO> list(Map<String, Object> map) {
        return agentDao.list(map);
    }

    @Override
    public int count(Map<String, Object> map) {
        return agentDao.count(map);
    }

    @Override
    public int save(AgentDO agent) {
        return agentDao.save(agent);
    }

    @Override
    public int update(AgentDO agent) {
        return agentDao.update(agent);
    }

    @Override
    public int remove(Integer agentId) {
        return agentDao.remove(agentId);
    }

    @Override
    public int batchRemove(Integer[] agentIds) {
        return agentDao.batchRemove(agentIds);
    }

    /**
     * 添加代理商
     *
     * @param agentVO 添加代理商需要的数据
     * @param userId  当前登录者ID
     * @return
     */
    @Override
    public R addAgent(AgentVO agentVO, Integer userId) throws Exception {
        //经销商信息
        AgentDO agentDO = agentVO.getAgentDO();
        //银行卡信息
        ValidList<BankcardVO> bankcardDOValidList = agentVO.getBankcardDOValidList();
        //合作协议信息
        ValidList<FileDO> fileValidList = agentVO.getFileValidList();
        //1.添加经销商
        agentDO.setAgentCreator(userId);
        int a = agentDao.save(agentDO);
        if (a <= 0) {
            return R.error();
        }
        Integer agentId = agentDO.getAgentId();
        //2.添加银行卡信息
        //3.添加经销商关联银行卡信息表
        for (BankcardVO bankcardVO : bankcardDOValidList) {
            BankcardDO bankcardDO = bankcardVO.getBankcardDO();
            bankcardDO.setBcCreuser(userId);
            String docUrl = OssUploadFileUtil.RandomFileName.uploadToOSS(bankcardVO.getBcPicUrl(), "loan/bankcard/" + bankcardDO.getBcNo());
            bankcardDO.setBcPicUrl(docUrl);
            int state = agentDao.saveBankcard(bankcardDO);
            AgentRelBankcardDO agentRelBankcardDO = new AgentRelBankcardDO();
            agentRelBankcardDO.setArbAgent(agentId);
            agentRelBankcardDO.setArbBcId(bankcardDO.getBcId());
            agentRelBankcardDO.setArbFlag(bankcardVO.getArbFlag());
            agentRelBankcardService.save(agentRelBankcardDO);
            if (state <= 0) {
                return R.error();
            }
        }
        //4.合作协议
        for (int fa = 0; fa < fileValidList.size(); fa++) {
            String str = System.currentTimeMillis() + agentId + "";
            String docUrl = OssUploadFileUtil.RandomFileName.uploadToOSS(fileValidList.get(fa).getFileUrl(), "loan/contract/company/" + str);
            fileValidList.get(fa).setFileUrl(docUrl);
            fileValidList.get(fa).setFileCreuser(userId);
            fileValidList.get(fa).setFileClassify(FileEnum.经销商.getValue());
            fileValidList.get(fa).setFileDataId(agentId + "");
            fileValidList.get(fa).setFilePrefix(str);
            fileValidList.get(fa).setFileSort(fa);
            fileValidList.get(fa).setFileName(str);
            int fileState = agentDao.saveFile(fileValidList.get(fa));
            if (fileState <= 0) {
                return R.error();
            }
        }

        return R.ok();
    }

    /**
     * 获取经销上信息 和 经销商的银行卡信息
     */
    @Override
    public List<AgentVO> agnetRelBankcardlist(Map map) {
        return agentDao.agnetRelBankcardlist(map);
    }

    /**
     * 获取合同信息
     */
    @Override
    public List<FileDO> fileList(Map map) {
        return agentDao.fileList(map);
    }


    /**
     * 获取 经销商信息，和 创建，修改 经销商信息的人的名字
     *
     * @param agentId
     * @return
     */
    @Override
    public AgentVO getAgentAndUser(Integer agentId) {
        return agentDao.getAgentAndUser(agentId);
    }

    @Override
    public List<AgentVO> getAgentAndUserList(Map map) {
        return agentDao.getAgentAndUserList(map);
    }

    @Override
    public R getAgent(Integer agentId) throws Exception {
        //1.获取代理商信息
        AgentVO agentVO = agentDao.getAgentAndUser(agentId);
        //2.获取银行卡信息
        Map map = new HashMap();
        map.put("agentId", agentId);
        List<AgentVO> agentVOList = agentDao.agnetRelBankcardlist(map);
        //3.获取合同信息
        Map fileMap = new HashMap();
        fileMap.put("fileClassify", FileEnum.经销商.getValue());
        fileMap.put("fileDataId", agentId + "");
        List<FileDO> fileDOList = agentDao.fileList(fileMap);
        //4.获取企业信息
        Map enterpriseMap = new HashMap();
        enterpriseMap.put("entId", agentVO.getAgentEntId());
        List<EnterpriseVO> enterpriseVOList = agentDao.enterpriseList(enterpriseMap);
        EnterpriseVO enterpriseVO = null;
        if (enterpriseVOList != null && enterpriseVOList.size() > 0) {
            enterpriseVO = enterpriseVOList.get(0);
        }
        R r = new R();
        r.put("agentVO", agentVO);
        r.put("bankcardDOValidList", agentVOList.get(0).getBankcardDOValidList());
        r.put("fileDOList", fileDOList);
        r.put("enterpriseVO", enterpriseVO);
        return r;
    }

    /**
     * 修改经销商信息
     *
     * @param agentVO 添加代理商需要的数据
     * @param userId  当前登录者ID
     * @return
     */
    @Override
    public R updateAgnet(AgentVO agentVO, Integer userId) throws Exception {
        AgentDO agentDO = agentVO.getAgentDO();
        ValidList<FileDO> fileValidList = agentVO.getFileValidList();
        List<BankcardVO> bankcardVOList = agentVO.getBankcardDOValidList();
        EnterpriseVO enterpriseVO = agentVO.getEnterpriseVO();
        Integer agentId = agentDO.getAgentId();
        //1.修改经销商信息
        agentDO.setAgentModuser(userId);
        if (agentDao.update(agentDO) <= 0) return R.error("经销商信息修改失败");
        //2.修改银行卡信息
        for (BankcardVO bankcardVO : bankcardVOList) {
            if (bankcardVO.getBcId() != null) { //执行修改操作
                bankcardVO.setBcModuser(userId);
                if (bankcardVO.getBcPicUrl() != null && bankcardVO.getBcPicUrl().indexOf("http") != 0) {
                    String docUrl = OssUploadFileUtil.RandomFileName.uploadToOSS(bankcardVO.getBcPicUrl(), "loan/bankcard/" + bankcardVO.getBcNo());
                    bankcardVO.setBcPicUrl(docUrl);
                }
                agentDao.updateBankcard(bankcardVO);
                AgentRelBankcardDO agentRelBankcardDO = new AgentRelBankcardDO();
                agentRelBankcardDO.setArbAgent(agentId);
                agentRelBankcardDO.setArbBcId(bankcardVO.getBcId());
                agentRelBankcardDO.setArbFlag(bankcardVO.getArbFlag());
                //查询银行卡 用图表ID
                Map map = new HashMap();
                map.put("arbBcId",bankcardVO.getBcId());
                map.put("arbAgent",agentId);
                List<AgentRelBankcardDO> agentRelBankcardDOList = agentRelBankcardService.list(map);
                for (AgentRelBankcardDO agentRelBankcardDO1:agentRelBankcardDOList) {
                    agentRelBankcardDO.setArbId(agentRelBankcardDO1.getArbId());
                }
                agentRelBankcardService.update(agentRelBankcardDO);
            } else { //执行添加操作
                //添加的话，要添加 经销商与银行卡关联表
                bankcardVO.setBcCreuser(userId);
                String docUrl = OssUploadFileUtil.RandomFileName.uploadToOSS(bankcardVO.getBcPicUrl(), "loan/bankcard/" + bankcardVO.getBcNo());
                bankcardVO.setBcPicUrl(docUrl);
                int state = agentDao.saveBankcard(bankcardVO);
                AgentRelBankcardDO agentRelBankcardDO = new AgentRelBankcardDO();
                agentRelBankcardDO.setArbAgent(agentId);
                agentRelBankcardDO.setArbBcId(bankcardVO.getBcId());
                agentRelBankcardDO.setArbFlag(bankcardVO.getArbFlag());
                agentRelBankcardService.save(agentRelBankcardDO);
                if (state <= 0) {
                    return R.error();
                }
            }
        }
        //3.修改合同信息
        //3.1 删除合同信息
        Map removeFile = new HashMap();
        removeFile.put("fileClassify", FileEnum.经销商.getValue());
        removeFile.put("fileDataId", agentId + "");
        agentDao.removeFile(removeFile);
        //3.2 重新添加合同信息
        if (fileValidList != null) {
            for (int fa = 0; fa < fileValidList.size(); fa++) {
                String str = System.currentTimeMillis() + agentId + "";
                if (fileValidList.get(fa).getFileUrl() != null && fileValidList.get(fa).getFileUrl().indexOf("http") != 0) {
                    String docUrl = OssUploadFileUtil.RandomFileName.uploadToOSS(fileValidList.get(fa).getFileUrl(), "loan/contract/company/" + str);
                    fileValidList.get(fa).setFileUrl(docUrl);
                }
                fileValidList.get(fa).setFileCreuser(userId);
                fileValidList.get(fa).setFileClassify(FileEnum.经销商.getValue());
                fileValidList.get(fa).setFileDataId(agentId + "");
                fileValidList.get(fa).setFilePrefix(str);
                fileValidList.get(fa).setFileSort(fa);
                fileValidList.get(fa).setFileName(str);
                int fileState = agentDao.saveFile(fileValidList.get(fa));
                if (fileState <= 0) {
                    return R.error();
                }
            }
        }
        //4.修改企业信息
        enterpriseVO.setEntModuser(userId);
        int a = agentDao.updateEnterprise(enterpriseVO);
        return R.ok();
    }

    /**
     * 删除银行卡信息
     *
     * @param bcId     银行卡ID
     * @param arbAgent 经销商ID
     * @return R
     */
    @Override
    public R deleteBancrad(Integer bcId, Integer arbAgent) {
        //1.删除银行卡信息
        adminBankcardFeignService.remove(bcId);
        //2.删除银行卡关联进销商
        Map map = new HashMap();
        map.put("arbAgent", arbAgent);
        map.put("arbBcId", bcId);
        List<AgentRelBankcardDO> agentRelBankcardDOList = agentRelBankcardService.list(map);
        for (AgentRelBankcardDO agentRelBankcardDO : agentRelBankcardDOList) {
            if (agentRelBankcardService.remove(agentRelBankcardDO.getArbId()) <= 0) return R.error("删除失败");
        }
        return R.ok();
    }


    /**
     * 添加营业执照
     *
     * @param enterprise
     * @param userId
     * @return
     */
    @Override
    public R saveEnterprise(EnterpriseDO enterprise, Integer userId) {
        enterprise.setEntCreuser(userId);
        if (enterprise.getEntSealPic() != null && enterprise.getEntSealPic() .indexOf("http") != 0) {
            String docUrl = OssUploadFileUtil.RandomFileName.uploadToOSS(enterprise.getEntSealPic() , "loan/ent/ent_seal/" + enterprise.getEntNo()+"seal");
            enterprise.setEntSealPic(docUrl);
        }
        if (enterprise.getEntLicensePic() != null && enterprise.getEntLicensePic() .indexOf("http") != 0) {
            String docUrl = OssUploadFileUtil.RandomFileName.uploadToOSS(enterprise.getEntLicensePic() , "loan/ent/ent_license/" + enterprise.getEntNo()+"license");
            enterprise.setEntLicensePic(docUrl);
        }
        adminEnterpriseFeignService.save(enterprise);
        return null;
    }

    @Override
    public List<BankcardVO> getBankcardList(Map map) {
        return agentDao.getBankcardList(map);
    }

    @Override
    public int getBankcardListcount(Map map) {
        return agentDao.getBankcardListcount(map);
    }

    @Override
    public R updateBankcard(BankcardVO bankcardVO, Integer userId) {
        //1. 修改银行卡信息 远程调用
        bankcardVO.setBcModuser(userId);
        if (bankcardVO.getBcPicUrl() != null && bankcardVO.getBcPicUrl().indexOf("http") != 0) {
            String docUrl = OssUploadFileUtil.RandomFileName.uploadToOSS(bankcardVO.getBcPicUrl(), "loan/bankcard/" + bankcardVO.getBcNo());
            bankcardVO.setBcPicUrl(docUrl);
        }
        adminBankcardFeignService.updateBankcard(bankcardVO);
        //2. 修改银行卡用途
        Map map = new HashMap();
        map.put("arbBcId", bankcardVO.getBcId());
        List<AgentRelBankcardDO> agentRelBankcardDOList = agentRelBankcardService.list(map);
        for (AgentRelBankcardDO agentRelBankcardDO : agentRelBankcardDOList) {
            agentRelBankcardDO.setArbFlag(bankcardVO.getArbFlag());
            agentRelBankcardService.update(agentRelBankcardDO);
        }
        return R.ok();
    }
}
